<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>xv6 实验六 Copy-on-Write Fork | kiloGrand</title><meta name="keywords" content="xv6"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;cow.html  在 xv6 系统中，fork() 系统调用会复制父进程的所有用户空间内存给子进程（正如我们在 pgtbl 实验中看到过的那样）。可是，如果父进程很大，复制过程会消耗很长的时间。更糟糕的">
<meta property="og:type" content="article">
<meta property="og:title" content="xv6 实验六 Copy-on-Write Fork">
<meta property="og:url" content="https://kilogrand.gitee.io/2022/09/05/xv6-lab6/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;cow.html  在 xv6 系统中，fork() 系统调用会复制父进程的所有用户空间内存给子进程（正如我们在 pgtbl 实验中看到过的那样）。可是，如果父进程很大，复制过程会消耗很长的时间。更糟糕的">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2022-09-05T01:41:10.000Z">
<meta property="article:modified_time" content="2023-02-28T02:17:49.555Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="xv6">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2022/09/05/xv6-lab6/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'xv6 实验六 Copy-on-Write Fork',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-02-28 10:17:49'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">xv6 实验六 Copy-on-Write Fork</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-09-05T01:41:10.000Z" title="发表于 2022-09-05 09:41:10">2022-09-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-02-28T02:17:49.555Z" title="更新于 2023-02-28 10:17:49">2023-02-28</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>14分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="xv6 实验六 Copy-on-Write Fork"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><ul>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/schedule.html">https://pdos.csail.mit.edu/6.S081/2020/schedule.html</a></li>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/labs/cow.html">https://pdos.csail.mit.edu/6.S081/2020/labs/cow.html</a></li>
</ul>
<p>在 xv6 系统中，fork() 系统调用会复制父进程的所有用户空间内存给子进程（正如我们在 pgtbl 实验中看到过的那样）。可是，如果父进程很大，复制过程会消耗很长的时间。更糟糕的是，这可能是无用功，例如 fork() 后子进程紧接着 exec()，那么刚复制下来的内存根本不会用到。另一方面，如果父子进程都要用到这块内存，那么复制又是必须的。</p>
<p>写时复制（Copy-on-Write）是一种计算机程序设计领域的优化策略。它的核心思想是，如果有多个呼叫者同时请求相同资源（如内存或磁盘上的数据存储），他们会共享相同的指针指向该资源，直到某个呼叫者试图修改资源内容时，系统才会真正复制一份专用副本给该呼叫者使用。这种技术通常用于文件系统、进程管理和虚拟内存等方面。</p>
<p>COW fork() 只给子进程创建一个页表，其 PTE 指向父进程的物理页，然后给父子进程的 PTE 全部打上<code>不可写</code>的标记。于是，当父子进程之一试图写这些页面时会产生 page fault，内核的 page fault 处理程序检测到这种情况后，给产生异常的那个进程分配一个新的页面，把原页面复制过去，修改 PTE 并打上<code>可写</code>的标记。处理程序返回之后，进程就能继续正常执行了。<br>COW fork() 让释放物理页面变得很 tricky，因为一个物理页面可能被多个进程的页表同时指向，因此只当最后一个指针撤去后才能释放。</p>
<h2 id="Implement-copy-on-write"><a href="#Implement-copy-on-write" class="headerlink" title="Implement copy-on-write"></a>Implement copy-on-write</h2><p>RISC-V 的 PTE 有 10 个标志位，其中第 8、9 位是为用户保留的，因此我用第 8 位作为 PTE_COW 标志，表示该 PTE 是否需要 copy-on-write：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/riscv.h</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> PTE_COW (1L &lt;&lt; 8) <span class="comment">// copy-on-write</span></span></span><br></pre></td></tr></table></figure></p>
<p>我们查看 fork() 的代码，发现页表复制是由 uvmcopy() 实现的，因此我们需要改的地方其实是 uvmcopy()。（我顺便查了一下还有没有其他函数调用了 uvmcopy()，结果惊奇地发现只有 fork() 调用了它）我们将开辟内存并复制内容的代码注释掉，改为直接向原空间建立映射，并把 PTE_W 置零，把 PTE_COW 置一<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line">// kernel/proc.c</span><br><span class="line">// Create a new process, copying the parent.</span><br><span class="line">// Sets up child kernel stack to return as if from fork() system call.</span><br><span class="line">int</span><br><span class="line">fork(void)</span><br><span class="line">&#123;</span><br><span class="line">  int i, pid;</span><br><span class="line">  struct proc *np;</span><br><span class="line">  struct proc *p = myproc();</span><br><span class="line"></span><br><span class="line">  // Allocate process.</span><br><span class="line">  if((np = allocproc()) == 0)&#123;</span><br><span class="line">    return -1;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  // Copy user memory from parent to child.</span><br><span class="line">  if(uvmcopy(p-&gt;pagetable, np-&gt;pagetable, p-&gt;sz) &lt; 0)&#123;</span><br><span class="line">    freeproc(np);</span><br><span class="line">    release(&amp;np-&gt;lock);</span><br><span class="line">    return -1;</span><br><span class="line">  &#125;</span><br><span class="line">  np-&gt;sz = p-&gt;sz;</span><br><span class="line"></span><br><span class="line">  np-&gt;parent = p;</span><br><span class="line"></span><br><span class="line">  // copy saved user registers.</span><br><span class="line">  *(np-&gt;trapframe) = *(p-&gt;trapframe);</span><br><span class="line"></span><br><span class="line">  // Cause fork to return 0 in the child.</span><br><span class="line">  np-&gt;trapframe-&gt;a0 = 0;</span><br><span class="line"></span><br><span class="line">  // increment reference counts on open file descriptors.</span><br><span class="line">  for(i = 0; i &lt; NOFILE; i++)</span><br><span class="line">    if(p-&gt;ofile[i])</span><br><span class="line">      np-&gt;ofile[i] = filedup(p-&gt;ofile[i]);</span><br><span class="line">  np-&gt;cwd = idup(p-&gt;cwd);</span><br><span class="line"></span><br><span class="line">  safestrcpy(np-&gt;name, p-&gt;name, sizeof(p-&gt;name));</span><br><span class="line"></span><br><span class="line">  pid = np-&gt;pid;</span><br><span class="line"></span><br><span class="line">  np-&gt;state = RUNNABLE;</span><br><span class="line"></span><br><span class="line">  release(&amp;np-&gt;lock);</span><br><span class="line"></span><br><span class="line">  return pid;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/vm.c</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">uvmcopy</span><span class="params">(<span class="type">pagetable_t</span> old, <span class="type">pagetable_t</span> new, uint64 sz)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">pte_t</span> *pte;</span><br><span class="line">  uint64 pa, i;</span><br><span class="line">  uint flags;</span><br><span class="line">  <span class="comment">//char *mem;</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; sz; i += PGSIZE)&#123;</span><br><span class="line">    <span class="keyword">if</span>((pte = walk(old, i, <span class="number">0</span>)) == <span class="number">0</span>)</span><br><span class="line">      panic(<span class="string">&quot;uvmcopy: pte should exist&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>((*pte &amp; PTE_V) == <span class="number">0</span>)</span><br><span class="line">      panic(<span class="string">&quot;uvmcopy: page not present&quot;</span>);</span><br><span class="line">    pa = PTE2PA(*pte);</span><br><span class="line">    flags = PTE_FLAGS(*pte);</span><br><span class="line">    <span class="comment">// xyf</span></span><br><span class="line">    flags = (flags | PTE_COW) &amp; (~PTE_W);</span><br><span class="line">    *pte = PA2PTE(pa) | flags;</span><br><span class="line">    <span class="keyword">if</span>(mappages(new, i, PGSIZE, pa, flags) != <span class="number">0</span>)</span><br><span class="line">      <span class="keyword">goto</span> err;</span><br><span class="line">    update_refcount(pa, <span class="number">1</span>);</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">    if((mem = kalloc()) == 0)</span></span><br><span class="line"><span class="comment">      goto err;</span></span><br><span class="line"><span class="comment">    memmove(mem, (char*)pa, PGSIZE);</span></span><br><span class="line"><span class="comment">    if(mappages(new, i, PGSIZE, (uint64)mem, flags) != 0)&#123;</span></span><br><span class="line"><span class="comment">      kfree(mem);</span></span><br><span class="line"><span class="comment">      goto err;</span></span><br><span class="line"><span class="comment">    &#125;*/</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"> err:</span><br><span class="line">  uvmunmap(new, <span class="number">0</span>, i / PGSIZE, <span class="number">1</span>);</span><br><span class="line">  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>update_refcount(pa, 1) 的作用后文叙述。</p>
<p>现在，对于某个带有 PTE_COW 标记的 PTE 指向的页面，我们写它时会引起 page fault——因为它的 PTE_W 被置零了。和上一个实验（lazy allocation）一样，这个 page fault 在 usertrap() 中处理。当写页面发生异常时，scause 寄存器的值会被置为 15，stval 寄存器会存储导致异常的地址，所以我们根据这两个寄存器处理 copy-on-write：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/trap.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">usertrap</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">int</span> which_dev = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>((r_sstatus() &amp; SSTATUS_SPP) != <span class="number">0</span>)</span><br><span class="line">    panic(<span class="string">&quot;usertrap: not from user mode&quot;</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// send interrupts and exceptions to kerneltrap(),</span></span><br><span class="line">  <span class="comment">// since we&#x27;re now in the kernel.</span></span><br><span class="line">  w_stvec((uint64)kernelvec);</span><br><span class="line"></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  </span><br><span class="line">  <span class="comment">// save user program counter.</span></span><br><span class="line">  p-&gt;trapframe-&gt;epc = r_sepc();</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">if</span>(r_scause() == <span class="number">8</span>)&#123;</span><br><span class="line">    <span class="comment">// system call</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(p-&gt;killed)</span><br><span class="line">      <span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// sepc points to the ecall instruction,</span></span><br><span class="line">    <span class="comment">// but we want to return to the next instruction.</span></span><br><span class="line">    p-&gt;trapframe-&gt;epc += <span class="number">4</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// an interrupt will change sstatus &amp;c registers,</span></span><br><span class="line">    <span class="comment">// so don&#x27;t enable until done with those registers.</span></span><br><span class="line">    intr_on();</span><br><span class="line"></span><br><span class="line">    syscall();</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span>((which_dev = devintr()) != <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="comment">// ok</span></span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// check cow</span></span><br><span class="line">    uint64 cause = r_scause();</span><br><span class="line">    <span class="keyword">if</span>(cause == <span class="number">15</span>)&#123;</span><br><span class="line">      <span class="comment">// page fault</span></span><br><span class="line">      uint64 stval = r_stval();</span><br><span class="line">      <span class="keyword">if</span>(handle_cow(p-&gt;pagetable, stval, <span class="number">0</span>) == <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">goto</span> brk; <span class="comment">// copy-on-write success</span></span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;usertrap(): unexpected scause %p pid=%d\n&quot;</span>, r_scause(), p-&gt;pid);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;            sepc=%p stval=%p\n&quot;</span>, r_sepc(), r_stval());</span><br><span class="line">    p-&gt;killed = <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">brk:</span><br><span class="line">  <span class="keyword">if</span>(p-&gt;killed)</span><br><span class="line">    <span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// give up the CPU if this is a timer interrupt.</span></span><br><span class="line">  <span class="keyword">if</span>(which_dev == <span class="number">2</span>)</span><br><span class="line">    yield();</span><br><span class="line"></span><br><span class="line">  usertrapret();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>其中 handle_cow() 函数处理 copy-on-write：它先解析虚拟地址，如果发现其 PTE 的 PTE_COW 被置位了，则开辟新的空间，并将 PTE 指向这个新的空间，同时把 PTE_W 置一、PTE_COW 置零。这样，当我们返回用户空间时，用户进程就能正常执行了：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/vm.c</span></span><br><span class="line"><span class="comment">// Check if virtual address refers to a cow page and handle it.</span></span><br><span class="line"><span class="comment">// Store the physical address of the newly allocated page in parameter newpa.</span></span><br><span class="line"><span class="comment">// Return: -1 something wrong</span></span><br><span class="line"><span class="comment">//          0 copy-on-write success</span></span><br><span class="line"><span class="comment">//          1 no need to copy-on-write</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">handle_cow</span><span class="params">(<span class="type">pagetable_t</span> pagetable, uint64 va, uint64 *newpa)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">pte_t</span> *pte = walk(pagetable, va, <span class="number">0</span>);</span><br><span class="line">  <span class="keyword">if</span>(pte == <span class="number">0</span>)  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="keyword">if</span>(*pte &amp; PTE_COW)&#123;</span><br><span class="line">    <span class="comment">// copy-on-write</span></span><br><span class="line">    uint flags = (PTE_FLAGS(*pte) &amp; (~PTE_COW)) | PTE_W;</span><br><span class="line">    uint64 pa = PTE2PA(*pte);</span><br><span class="line">    <span class="type">char</span> *mem = kalloc();</span><br><span class="line">    <span class="keyword">if</span>(mem == <span class="number">0</span>)  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    memmove(mem, (<span class="type">char</span> *)pa, PGSIZE);</span><br><span class="line">    *pte = PA2PTE((uint64)mem) | flags;</span><br><span class="line">    kfree((<span class="type">void</span> *)pa);</span><br><span class="line">    <span class="keyword">if</span>(newpa) *newpa = (uint64)mem;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>为了方便，我传入了一个指针以保存新的物理地址，待会儿会用到。<br>同时在kernel/defs.h声明</p>
<p>copy-on-write 之后，原来的页面怎么办呢？在上面的代码中，我调用了 kfree 试图将其释放。但正如前文所述，只有当所有进程都不用一个页面时才能将其释放，所以我们需要开一个计数数组，对每一个页面统计有多少个进程指向了它。那一共有多少个页面呢？之前做第三个实验（page tables）的时候我们学习了，xv6（内核进程会用到）的内核空间是从 KERNBASE 到 PHYSTOP 的一段，所以一共有 (PHYSTOP-KERNBASE)/PGSIZE 页，并且物理地址 pa 在第 (pa-KERNBASE)/PGSIZE 页中，我们以此作为计数数组下标即可：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/kalloc.c</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> idx(x) (((uint64)(x)-KERNBASE)/PGSIZE)</span></span><br><span class="line"><span class="type">int</span> refcount[idx(PHYSTOP)];</span><br></pre></td></tr></table></figure></p>
<p>每次 kalloc() 时，设置当前计数为 1；kfree 时，计数自减，如果减到了零，才释放内存：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/kalloc.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">kfree</span><span class="params">(<span class="type">void</span> *pa)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">if</span>(((uint64)pa % PGSIZE) != <span class="number">0</span> || (<span class="type">char</span>*)pa &lt; end || (uint64)pa &gt;= PHYSTOP)</span><br><span class="line">    panic(<span class="string">&quot;kfree&quot;</span>);</span><br><span class="line">  <span class="comment">// Free only when the last reference goes away.</span></span><br><span class="line">  <span class="keyword">if</span>((uint64)pa &gt;= KERNBASE)&#123;</span><br><span class="line">    <span class="keyword">if</span>(refcount[idx(pa)] &lt;= <span class="number">0</span>)</span><br><span class="line">      panic(<span class="string">&quot;kfree: refcount&quot;</span>);</span><br><span class="line">    <span class="keyword">if</span>(--refcount[idx(pa)]) <span class="keyword">return</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="type">void</span> *</span><br><span class="line"><span class="title function_">kalloc</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">if</span>(r)</span><br><span class="line">    refcount[idx(r)] = <span class="number">1</span>;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>值得注意的是，kinit() 初始化是调用 kfree() 实现的，所以为了把计数数组初始化为零，可以在 freerange 中把所有页的计数置为 1，这样调用一次 kfree()，就能把计数置零、加入 kmem.freelist：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/kalloc.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">freerange</span><span class="params">(<span class="type">void</span> *pa_start, <span class="type">void</span> *pa_end)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="type">char</span> *p;</span><br><span class="line">  p = (<span class="type">char</span>*)PGROUNDUP((uint64)pa_start);</span><br><span class="line">  <span class="keyword">for</span>(; p + PGSIZE &lt;= (<span class="type">char</span>*)pa_end; p += PGSIZE)&#123;</span><br><span class="line">    refcount[idx(p)] = <span class="number">1</span>;</span><br><span class="line">    kfree(p);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>为了让 kalloc.c 之外的函数方便地对 refcount 操作，我写了一个更新函数：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/kalloc.c</span></span><br><span class="line"><span class="comment">// Update refcount</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">update_refcount</span><span class="params">(uint64 pa, <span class="type">int</span> val)</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="keyword">if</span>((pa % PGSIZE) != <span class="number">0</span> || pa &lt; KERNBASE || pa &gt;= PHYSTOP)</span><br><span class="line">    panic(<span class="string">&quot;update_refcount&quot;</span>);</span><br><span class="line">  refcount[idx(pa)] += val;</span><br><span class="line">  <span class="keyword">if</span>(refcount[idx(pa)] &lt; <span class="number">0</span>)</span><br><span class="line">    panic(<span class="string">&quot;update_refcount: less than 0&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>上文 uvmcopy 就调用了它使得计数加一。<br>在kernel/defs.h添加声明</p>
<p>最后，我们还需要改 copyout，也用 handle_cow 函数即可，这里我设置的第三个参数就发挥了作用，当然不设置这个参数，之后 walkaddr 一下也行。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/kalloc.c</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">copyout</span><span class="params">(<span class="type">pagetable_t</span> pagetable, uint64 dstva, <span class="type">char</span> *src, uint64 len)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">while</span>(len &gt; <span class="number">0</span>)&#123;</span><br><span class="line">    va0 = PGROUNDDOWN(dstva);</span><br><span class="line">    pa0 = walkaddr(pagetable, va0);</span><br><span class="line">    <span class="keyword">if</span>(pa0 == <span class="number">0</span>)</span><br><span class="line">      <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    <span class="keyword">if</span>(handle_cow(pagetable, va0, &amp;pa0) == <span class="number">-1</span>)</span><br><span class="line">      <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="make-grade"><a href="#make-grade" class="headerlink" title="make grade"></a>make grade</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">== Test running cowtest == </span><br><span class="line">$ make qemu-gdb</span><br><span class="line">(26.1s) </span><br><span class="line">== Test   simple == </span><br><span class="line">  simple: OK </span><br><span class="line">== Test   three == </span><br><span class="line">  three: OK </span><br><span class="line">== Test   file == </span><br><span class="line">  file: OK </span><br><span class="line">== Test usertests == </span><br><span class="line">$ make qemu-gdb</span><br><span class="line">(364.4s) </span><br><span class="line">    (Old xv6.out.usertests failure <span class="built_in">log</span> removed)</span><br><span class="line">== Test   usertests: copyin == </span><br><span class="line">  usertests: copyin: OK </span><br><span class="line">== Test   usertests: copyout == </span><br><span class="line">  usertests: copyout: OK </span><br><span class="line">== Test   usertests: all tests == </span><br><span class="line">  usertests: all tests: OK </span><br><span class="line">== Test time == </span><br><span class="line">time: OK </span><br><span class="line">Score: 110/110</span><br></pre></td></tr></table></figure>
<h2 id="git-diff"><a href="#git-diff" class="headerlink" title="git diff"></a>git diff</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br></pre></td><td class="code"><pre><span class="line">diff --git a/grade-lab-cow b/grade-lab-cow</span><br><span class="line">index 8eff3b7..0d19e6d 100755</span><br><span class="line">--- a/grade-lab-cow</span><br><span class="line">+++ b/grade-lab-cow</span><br><span class="line">@@ -29,7 +29,7 @@ def test_file():</span><br><span class="line"> def test_usertests():</span><br><span class="line">     r.run_qemu(shell_script([</span><br><span class="line">         <span class="string">&#x27;usertests&#x27;</span></span><br><span class="line">-    ]), <span class="built_in">timeout</span>=300)</span><br><span class="line">+    ]), <span class="built_in">timeout</span>=1000)</span><br><span class="line">     r.match(<span class="string">&#x27;^ALL TESTS PASSED$&#x27;</span>)</span><br><span class="line"> </span><br><span class="line"> def usertest_check(testcase, nextcase, output):</span><br><span class="line">diff --git a/kernel/defs.h b/kernel/defs.h</span><br><span class="line">index 4b9bbc0..4e8e7bc 100644</span><br><span class="line">--- a/kernel/defs.h</span><br><span class="line">+++ b/kernel/defs.h</span><br><span class="line">@@ -63,6 +63,7 @@ void            ramdiskrw(struct buf*);</span><br><span class="line"> void*           kalloc(void);</span><br><span class="line"> void            kfree(void *);</span><br><span class="line"> void            kinit(void);</span><br><span class="line">+void            update_refcount(uint64, int);</span><br><span class="line"> </span><br><span class="line"> // log.c</span><br><span class="line"> void            initlog(int, struct superblock*);</span><br><span class="line">@@ -171,6 +172,7 @@ uint64          walkaddr(pagetable_t, uint64);</span><br><span class="line"> int             copyout(pagetable_t, uint64, char *, uint64);</span><br><span class="line"> int             copyin(pagetable_t, char *, uint64, uint64);</span><br><span class="line"> int             copyinstr(pagetable_t, char *, uint64, uint64);</span><br><span class="line">+int             handle_cow(pagetable_t, uint64, uint64 *);</span><br><span class="line"> </span><br><span class="line"> // plic.c</span><br><span class="line"> void            plicinit(void);</span><br><span class="line">diff --git a/kernel/kalloc.c b/kernel/kalloc.c</span><br><span class="line">index fa6a0ac..8ecec14 100644</span><br><span class="line">--- a/kernel/kalloc.c</span><br><span class="line">+++ b/kernel/kalloc.c</span><br><span class="line">@@ -23,6 +23,9 @@ struct &#123;</span><br><span class="line">   struct run *freelist;</span><br><span class="line"> &#125; kmem;</span><br><span class="line"> </span><br><span class="line">+<span class="comment">#define idx(x) (((uint64)(x)-KERNBASE)/PGSIZE)</span></span><br><span class="line">+int refcount[idx(PHYSTOP)];</span><br><span class="line">+</span><br><span class="line"> void</span><br><span class="line"> <span class="function"><span class="title">kinit</span></span>()</span><br><span class="line"> &#123;</span><br><span class="line">@@ -35,8 +38,10 @@ freerange(void *pa_start, void *pa_end)</span><br><span class="line"> &#123;</span><br><span class="line">   char *p;</span><br><span class="line">   p = (char*)PGROUNDUP((uint64)pa_start);</span><br><span class="line">-  <span class="keyword">for</span>(; p + PGSIZE &lt;= (char*)pa_end; p += PGSIZE)</span><br><span class="line">+  <span class="keyword">for</span>(; p + PGSIZE &lt;= (char*)pa_end; p += PGSIZE)&#123;</span><br><span class="line">+    refcount[idx(p)] = 1;</span><br><span class="line">     kfree(p);</span><br><span class="line">+  &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> // Free the page of physical memory pointed at by v,</span><br><span class="line">@@ -50,7 +55,14 @@ kfree(void *pa)</span><br><span class="line"> </span><br><span class="line">   <span class="keyword">if</span>(((uint64)pa % PGSIZE) != 0 || (char*)pa &lt; end || (uint64)pa &gt;= PHYSTOP)</span><br><span class="line">     panic(<span class="string">&quot;kfree&quot;</span>);</span><br><span class="line">-</span><br><span class="line">+  </span><br><span class="line">+  // Free only when the last reference goes away.</span><br><span class="line">+  <span class="keyword">if</span>((uint64)pa &gt;= KERNBASE)&#123;</span><br><span class="line">+    <span class="keyword">if</span>(refcount[idx(pa)] &lt;= 0)</span><br><span class="line">+      panic(<span class="string">&quot;kfree: refcount&quot;</span>);</span><br><span class="line">+    <span class="keyword">if</span>(--refcount[idx(pa)]) <span class="built_in">return</span>;</span><br><span class="line">+  &#125;</span><br><span class="line">+  </span><br><span class="line">   // Fill with junk to catch dangling refs.</span><br><span class="line">   memset(pa, 1, PGSIZE);</span><br><span class="line"> </span><br><span class="line">@@ -78,5 +90,20 @@ kalloc(void)</span><br><span class="line"> </span><br><span class="line">   <span class="keyword">if</span>(r)</span><br><span class="line">     memset((char*)r, 5, PGSIZE); // fill with junk</span><br><span class="line">+</span><br><span class="line">+  <span class="keyword">if</span>(r)</span><br><span class="line">+    refcount[idx(r)] = 1;</span><br><span class="line">+ </span><br><span class="line">   <span class="built_in">return</span> (void*)r;</span><br><span class="line"> &#125;</span><br><span class="line">+</span><br><span class="line">+// Update refcount</span><br><span class="line">+void</span><br><span class="line">+update_refcount(uint64 pa, int val)</span><br><span class="line">+&#123;</span><br><span class="line">+  <span class="keyword">if</span>((pa % PGSIZE) != 0 || pa &lt; KERNBASE || pa &gt;= PHYSTOP)</span><br><span class="line">+    panic(<span class="string">&quot;update_refcount&quot;</span>);</span><br><span class="line">+  refcount[idx(pa)] += val;</span><br><span class="line">+  <span class="keyword">if</span>(refcount[idx(pa)] &lt; 0)</span><br><span class="line">+    panic(<span class="string">&quot;update_refcount: less than 0&quot;</span>);</span><br><span class="line">+&#125;</span><br><span class="line">diff --git a/kernel/riscv.h b/kernel/riscv.h</span><br><span class="line">index 0aec003..8a0ca5f 100644</span><br><span class="line">--- a/kernel/riscv.h</span><br><span class="line">+++ b/kernel/riscv.h</span><br><span class="line">@@ -331,6 +331,7 @@ sfence_vma()</span><br><span class="line"> <span class="comment">#define PTE_W (1L &lt;&lt; 2)</span></span><br><span class="line"> <span class="comment">#define PTE_X (1L &lt;&lt; 3)</span></span><br><span class="line"> <span class="comment">#define PTE_U (1L &lt;&lt; 4) // 1 -&gt; user can access</span></span><br><span class="line">+<span class="comment">#define PTE_COW (1L &lt;&lt; 8)  // used in copy-on-write</span></span><br><span class="line"> </span><br><span class="line"> // <span class="built_in">shift</span> a physical address to the right place <span class="keyword">for</span> a PTE.</span><br><span class="line"> <span class="comment">#define PA2PTE(pa) ((((uint64)pa) &gt;&gt; 12) &lt;&lt; 10)</span></span><br><span class="line">diff --git a/kernel/trap.c b/kernel/trap.c</span><br><span class="line">index a63249e..b0bf1bb 100644</span><br><span class="line">--- a/kernel/trap.c</span><br><span class="line">+++ b/kernel/trap.c</span><br><span class="line">@@ -68,11 +68,21 @@ usertrap(void)</span><br><span class="line">   &#125; <span class="keyword">else</span> <span class="keyword">if</span>((which_dev = devintr()) != 0)&#123;</span><br><span class="line">     // ok</span><br><span class="line">   &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">+    // check cow</span><br><span class="line">+    uint64 cause = r_scause();</span><br><span class="line">+    <span class="keyword">if</span>(cause == 15)&#123;</span><br><span class="line">+      // page fault</span><br><span class="line">+      uint64 stval = r_stval();</span><br><span class="line">+      <span class="keyword">if</span>(handle_cow(p-&gt;pagetable, stval, 0) == 0)</span><br><span class="line">+        goto brk;</span><br><span class="line">+    &#125;</span><br><span class="line">+    </span><br><span class="line">     <span class="built_in">printf</span>(<span class="string">&quot;usertrap(): unexpected scause %p pid=%d\n&quot;</span>, r_scause(), p-&gt;pid);</span><br><span class="line">     <span class="built_in">printf</span>(<span class="string">&quot;            sepc=%p stval=%p\n&quot;</span>, r_sepc(), r_stval());</span><br><span class="line">     p-&gt;killed = 1;</span><br><span class="line">   &#125;</span><br><span class="line"> </span><br><span class="line">+brk:</span><br><span class="line">   <span class="keyword">if</span>(p-&gt;killed)</span><br><span class="line">     <span class="built_in">exit</span>(-1);</span><br><span class="line"> </span><br><span class="line">diff --git a/kernel/vm.c b/kernel/vm.c</span><br><span class="line">index bccb405..88c444d 100644</span><br><span class="line">--- a/kernel/vm.c</span><br><span class="line">+++ b/kernel/vm.c</span><br><span class="line">@@ -311,7 +311,7 @@ uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)</span><br><span class="line">   pte_t *pte;</span><br><span class="line">   uint64 pa, i;</span><br><span class="line">   uint flags;</span><br><span class="line">-  char *mem;</span><br><span class="line">+  //char *mem;</span><br><span class="line"> </span><br><span class="line">   <span class="keyword">for</span>(i = 0; i &lt; sz; i += PGSIZE)&#123;</span><br><span class="line">     <span class="keyword">if</span>((pte = walk(old, i, 0)) == 0)</span><br><span class="line">@@ -320,6 +320,13 @@ uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)</span><br><span class="line">       panic(<span class="string">&quot;uvmcopy: page not present&quot;</span>);</span><br><span class="line">     pa = PTE2PA(*pte);</span><br><span class="line">     flags = PTE_FLAGS(*pte);</span><br><span class="line">+</span><br><span class="line">+    flags = (flags | PTE_COW) &amp; (~PTE_W);</span><br><span class="line">+    *pte = PA2PTE(pa) | flags;</span><br><span class="line">+    <span class="keyword">if</span>(mappages(new, i, PGSIZE, pa, flags) != 0)</span><br><span class="line">+      goto err;</span><br><span class="line">+    update_refcount(pa, 1);</span><br><span class="line">+/*</span><br><span class="line">     <span class="keyword">if</span>((mem = kalloc()) == 0)</span><br><span class="line">       goto err;</span><br><span class="line">     memmove(mem, (char*)pa, PGSIZE);</span><br><span class="line">@@ -327,6 +334,7 @@ uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)</span><br><span class="line">       kfree(mem);</span><br><span class="line">       goto err;</span><br><span class="line">     &#125;</span><br><span class="line">+*/</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="built_in">return</span> 0;</span><br><span class="line"> </span><br><span class="line">@@ -361,6 +369,10 @@ copyout(pagetable_t pagetable, uint64 dstva, char *src, uint64 len)</span><br><span class="line">     pa0 = walkaddr(pagetable, va0);</span><br><span class="line">     <span class="keyword">if</span>(pa0 == 0)</span><br><span class="line">       <span class="built_in">return</span> -1;</span><br><span class="line">+</span><br><span class="line">+    <span class="keyword">if</span>(handle_cow(pagetable, va0, &amp;pa0) == -1)</span><br><span class="line">+      <span class="built_in">return</span> -1;</span><br><span class="line">+</span><br><span class="line">     n = PGSIZE - (dstva - va0);</span><br><span class="line">     <span class="keyword">if</span>(n &gt; len)</span><br><span class="line">       n = len;</span><br><span class="line">@@ -440,3 +452,28 @@ copyinstr(pagetable_t pagetable, char *dst, uint64 srcva, uint64 max)</span><br><span class="line">     <span class="built_in">return</span> -1;</span><br><span class="line">   &#125;</span><br><span class="line"> &#125;</span><br><span class="line">+</span><br><span class="line">+// Check <span class="keyword">if</span> virtual address refers to a cow page and handle it.</span><br><span class="line">+// Store the physical address of the newly allocated page <span class="keyword">in</span> parameter newpa.</span><br><span class="line">+// Return: -1 something wrong</span><br><span class="line">+//          0 copy-on-write success</span><br><span class="line">+//          1 no need to copy-on-write</span><br><span class="line">+int</span><br><span class="line">+handle_cow(pagetable_t pagetable, uint64 va, uint64 *newpa)</span><br><span class="line">+&#123;</span><br><span class="line">+  pte_t *pte = walk(pagetable, va, 0);</span><br><span class="line">+  <span class="keyword">if</span>(pte == 0)  <span class="built_in">return</span> -1;</span><br><span class="line">+  <span class="keyword">if</span>(*pte &amp; PTE_COW)&#123;</span><br><span class="line">+    // copy-on-write</span><br><span class="line">+    uint flags = (PTE_FLAGS(*pte) &amp; (~PTE_COW)) | PTE_W;</span><br><span class="line">+    uint64 pa = PTE2PA(*pte);</span><br><span class="line">+    char *mem = kalloc();</span><br><span class="line">+    <span class="keyword">if</span>(mem == 0)  <span class="built_in">return</span> -1;</span><br><span class="line">+    memmove(mem, (char *)pa, PGSIZE);</span><br><span class="line">+    *pte = PA2PTE((uint64)mem) | flags;</span><br><span class="line">+    kfree((void *)pa);</span><br><span class="line">+    <span class="keyword">if</span>(newpa) *newpa = (uint64)mem;</span><br><span class="line">+    <span class="built_in">return</span> 0;</span><br><span class="line">+  &#125;</span><br><span class="line">+  <span class="built_in">return</span> 1;</span><br><span class="line">+&#125;</span><br><span class="line">diff --git a/time.txt b/time.txt</span><br><span class="line">new file mode 100644</span><br><span class="line">index 0000000..f599e28</span><br><span class="line">--- /dev/null</span><br><span class="line">+++ b/time.txt</span><br><span class="line">@@ -0,0 +1 @@</span><br><span class="line">+10</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2022/09/05/xv6-lab6/">https://kilogrand.gitee.io/2022/09/05/xv6-lab6/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/xv6/">xv6</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/09/04/xv6-lab4/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">xv6 实验4 Traps</div></div></a></div><div class="next-post pull-right"><a href="/2022/09/05/xv6-lab5/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">xv6 实验五 lazy page allocation</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/08/31/xv6-Chapter-0/" title="xv6 riscv book 中文版声明"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 riscv book 中文版声明</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-1/" title="xv6 第一章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第一章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-2/" title="xv6 第二章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第二章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-3/" title="xv6 第三章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第三章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-4/" title="xv6 第四章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第四章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-5/" title="xv6 第五章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第五章</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Implement-copy-on-write"><span class="toc-number">1.</span> <span class="toc-text">Implement copy-on-write</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#make-grade"><span class="toc-number">2.</span> <span class="toc-text">make grade</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#git-diff"><span class="toc-number">3.</span> <span class="toc-text">git diff</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>